package org.onepiece.admin.common.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @author zhujianke@gaodun.com
 * @since 2023/2/23 09:35
 */
@Data
public class CommonPage<T> {

    /**
     * 查询数据列表
     */
    private List<T> records = Collections.emptyList();

    /**
     * 总数
     */
    private long total = 0;

    /**
     * 当前分页总页数
     */
    private long pages = 1;

    /**
     * 每页显示条数，默认 10
     */
    private long size = 10;

    /**
     * 当前页
     */
    private long current = 1;

    /**
     * 基于 Mybatis-plus 的 {@link com.baomidou.mybatisplus.extension.plugins.pagination.Page} 构建
     *
     * @param page Mybatis-plus的分页对象
     * @return CommonPage
     */
    private static <T, R> CommonPage<R> create(Page<T> page) {
        CommonPage<R> commonPage = new CommonPage<>();
        commonPage.total = page.getTotal();
        commonPage.pages = page.getPages();
        commonPage.current = page.getCurrent();
        commonPage.size = page.getSize();
        return commonPage;
    }

    public static <T> CommonPage<T> build(Page<T> page) {
        CommonPage<T> commonPage = create(page);
        commonPage.records = page.getRecords();
        return commonPage;
    }

    public static <T, R> CommonPage<R> buildByFunction(Page<T> page, Function<T, R> transferFunction) {
        CommonPage<R> commonPage = create(page);
        commonPage.records = page.getRecords().stream().map(transferFunction).collect(Collectors.toList());
        return commonPage;
    }

    public static <T, R> CommonPage<R> buildByListTransfer(Page<T> page, Function<List<T>, List<R>> listTransferFunction) {
        CommonPage<R> commonPage = create(page);
        commonPage.records = listTransferFunction.apply(page.getRecords());
        return commonPage;
    }

    public static <T, R> CommonPage<R> buildByOtherList(Page<T> page, List<R> otherList) {
        CommonPage<R> commonPage = create(page);
        commonPage.records = otherList;
        return commonPage;
    }

    public static <T> CommonPage<T> empty(long current, long size) {
        CommonPage<T> commonPage = new CommonPage<>();
        commonPage.current = current;
        commonPage.size = size;
        return commonPage;
    }

}
